/**
 * @(#)ApkSimulatorTimer.java 2017年03月25日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.BaseThread;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.channel.ClientTaskInfo;
import org.jsbd.boss.service.ISimulatorListenService;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;

/**
 * 模拟器升级
 * 
 * @author <a href="mailto:wangjunbiao@zhexinit.com" >王俊标</a>
 * @version 1.0.0
 */
public class OTAUpgradeTimer extends BaseThread {
	public static final Logger LOGGER = LoggerFactory.getLogger(OTAUpgradeTimer.class);

	@Autowired
	private ISimulatorListenService simulatorListenService;
	@Autowired
	private RedisClient<String, Object> redisClient;

	private long cycleTime = 600 * 1000;

	@Override
	public void start() {
		LOGGER.info("OTA UPGRADE START");
		
		long ttl = 0l;
		if (redisClient.hasKey(CacheKey.UPGRADE_SYSTEM_LIST)) {
			cycleTime = Long.valueOf(String.valueOf(redisClient.get(CacheKey.UPGRADE_SYSTEM_INTERVAL_TIME)));
			ttl = (cycleTime * 60)-10;
		} else {
			ttl = 1;
		}
		
		try {
			if (redisClient.evalSetNx(CacheKey.UPGRADE_SYSTEM_LOCK_KEY, ttl)) {
				long startTime = System.currentTimeMillis();
				if (redisClient.hasKey(CacheKey.UPGRADE_SYSTEM_LIST)) {
					//cycleTime = Long.valueOf(String.valueOf(redisClient.get(CacheKey.UPGRADE_SYSTEM_INTERVAL_TIME)));
					cycleTime = cycleTime * 60 * 1000;
					super.setCycleTime(cycleTime);
					int num = (int) redisClient.get(CacheKey.UPGRADE_SYSTEM_NUM);
					int orderType = (int) redisClient.get(CacheKey.UPGRADE_SYSTEM_ORDER_TYPE);
					String taskContent = (String) redisClient.get(CacheKey.UPGRADE_SYSTEM_TASK_CONTENT);

					ClientTaskInfo taskInfo = new ClientTaskInfo();
					taskInfo.setTaskId(UUID.randomUUID().toString().replace("-", ""));
					taskInfo.setOrderType(orderType);
					if (StringUtils.isNotBlank(taskContent)) {
						taskInfo.setTaskContent(JSON.parseObject(taskContent));
					}

					Map<String, Object> dataMap = new HashMap<String, Object>();
					List<Object> keyList = new ArrayList<Object>();
					for (int i = 0; i < num; i++) {
						if (dataMap.size() < num) {
							keyList.clear();
							String uuid = String.valueOf(redisClient.pollFromQueue(CacheKey.UPGRADE_SYSTEM_LIST));
							keyList.add(uuid);
							boolean hasTask = simulatorListenService.hasTask(keyList);
							if (hasTask) {
								redisClient.putToQueue(CacheKey.UPGRADE_SYSTEM_LIST, uuid);
								continue;
							}
							dataMap.put(uuid, taskInfo);
						}
					}
					simulatorListenService.addTask(dataMap);
				}
				long endTime = System.currentTimeMillis();
				long interval = endTime-startTime;
				System.out.println("OTAUpgradeTimer interval time: " + interval);
			}
		} catch (Exception e) {
			LOGGER.error("OTA升级异常:", e);
		} 
	}
}
